package com.oneonefive.educationsystem.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.util.internal.StringUtil;

import javax.xml.crypto.Data;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//判断实体类各个属性是否为空
public  class ReflectUtil<T> {

    public void swaggerCheck(T t, QueryWrapper<T> wrapper, Class clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            name = checkName(name);
            Object o = getFieldValueByName(field.getName(), t);
            if (field.getGenericType().equals(String.class)) {
                if (!StringUtil.isNullOrEmpty((String) o)) {
                    wrapper.like(name, o);
                }
            } else if (field.getGenericType().equals(Integer.class)) {
                if (o != null) {
                    wrapper.eq(name, o);
                }
            } else if (field.getGenericType().equals(Data.class)) {
                if (o != null) {
                    wrapper.ge(name, o);
                }
            }
        }
    }
    public  String  checkName(String name) {
        int len = name.length();
        for (int i = 0; i < len; i++) {
            char c = name.charAt(i);
            if (c >= 'a' && c <= 'z') {
                continue;
            }
            c -= 'A' - 'a';
            name = name.substring(0, i) + "_" + c + name.substring(i + 1);
        }
        return name;
    }

    public  Object getFieldValueByName(String filedName, Object o) {
        try {
            String firstLetter = filedName.substring(0,1).toUpperCase();
            String getter = "get"+firstLetter+filedName.substring(1);
            Method method =o.getClass().getMethod(getter);
            return method.invoke(o);
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
